package net.classes;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.bd.MySQL;
import net.wfsim.clusterizer.*;
import net.wfsim.loader.BancoDeDados;
import net.wfsim.loader.ClusterSerializer;
import net.wfsim.matching.similarity.SimilarityMetric;
import net.wfsim.matching.similarity.TFIDFMetric;
import net.wfsim.structures.form.FormElement;

public class Clusterizer {

	public static SimilarityMetric<String> defaultValueMetric = new TFIDFMetric();
	
	public static void run() {
		
		List<FormElement> elements;
		BancoDeDados bd;
		int clusterId;
		Map<FormElement, List<FormElement>> cluster;
		
		PreparedStatement s = null;
		ResultSet result;
		String vSqlInsert = "select centroid\n" +
				      	    "  from cluster\n" +
				      	    " where modified = ? ";
		
		String vSqlCluster = "delete\n" +
			      			 "  from cluster\n" +
			      			 " where centroid = ? ";
		
		String vSqlClusterToElement = "delete\n" +
			      					  "  from cluster_to_element\n" +
			      					  " where cluster = ? ";
		
		bd = new BancoDeDados();
		MySQL.inicializaBD();
		
		try {
			s = (PreparedStatement) MySQL.getStatement().getConnection().prepareStatement(vSqlInsert);
			s.setInt(1, 1);
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
				
		result = MySQL.select(s);
		
		elements = new ArrayList<FormElement>();
		
		try {
			while (result.next()){
				clusterId = result.getInt("centroid");
				elements.addAll(bd.selectElementsFromCluster(clusterId));
				
				s = (PreparedStatement) MySQL.getStatement().getConnection().prepareStatement(vSqlClusterToElement);
				s.setInt(1, clusterId);
				MySQL.dml(s);
				
				s = (PreparedStatement) MySQL.getStatement().getConnection().prepareStatement(vSqlCluster);
				s.setInt(1, clusterId);
				MySQL.dml(s);
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		FormElementClusterizerTrainable clusterizer = new FormElementClusterizerTrainable();
        clusterizer.setElements(elements);
        
        clusterizer.setTextValueMetric(defaultValueMetric);

        Date start = new Date();
        System.out.println(start.toString());
        
        cluster = clusterizer.clusterizeAsMap();
        
        Date end = new Date();
        System.out.println(end.toString());
                
		MySQL.insertClusterization(cluster);	
		
	}
	
	

	
	
}
